package Arrays;

public class _747_LargestNumberAtLeastTwiceofOthers {
    public int dominantIndex(int[] nums) {
        int max = Integer.MIN_VALUE;
        int length = nums.length;
        int maxPos = 0;
        for(int i=0;i<length;i++){
            int tempVal = nums[i];
            if(max<tempVal){
                max = tempVal;
                maxPos = i;
            }
        }
        //如果 && 中放入多个条件，则一次为假即停止循环
        for(int i=0;i<length;i++){
            if(i!=maxPos) {
                if (max < nums[i] * 2) {
                    return -1;
                }
            }
        }
        return maxPos;
    }

    //法二，使用次小值，速度更慢……
    public int dominantIndex1(int[] nums){
        int length = nums.length;
        int max = Integer.MIN_VALUE;
        int secondMax = -1;
        int maxPos = 0;
        for(int i=0;i<length;i++){
            if(max<nums[i]){
                int temp = max;
                max = nums[i];
                if(temp*2>max){
                    secondMax = temp*2;
                }else{
                    maxPos = i;
                }
            }else{
                if(nums[i]*2>max){
                    secondMax = nums[i] *2;
                }
            }
        }
        if(secondMax!=-1 && secondMax>max){
            return -1;
        }
        return maxPos;
    }
}
